﻿using sqlsearcher.Services.IService;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace sqlsearcher.Services
{
    public class SqlServerHelper:ISqlHelper
    {
        public static string SERVER = string.Empty;
        public static string CONNSTR = string.Empty;

        private string server;
        private string uid;
        private string pwd;
        private string dbName;
        private int dbType;
        private static string ConnectionString = string.Empty;
        public SqlServerHelper(string server, string uid, string pwd,int dbType)
        {
            SERVER = server;
            this.server = server;
            this.uid = uid;
            this.pwd = pwd;
            this.dbType = dbType;
        }

        public SqlServerHelper(string server, string uid, string pwd, string dbName)
        {
            SERVER = server;
            this.dbName = dbName;
            this.server = server;
            this.uid = uid;
            this.pwd = pwd;
        }
        public bool TryConn()
        {
            var isConn = false;
            using (SqlConnection conn = new SqlConnection(this.GetConnStr()))
            {
                try
                {
                    conn.Open();
                    isConn = true;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    conn.Close();
                }
            }
             return isConn;
        }


        public string GetConnStr()
        {
            var con1 = "Data Source=$server;User ID=$uid;Password=$pwd";

            var con2 = "Data Source=$server,User ID=$uid,Password=$pwd,Initial Catalog=$database";

            if (string.IsNullOrEmpty(this.server) || string.IsNullOrEmpty(this.uid) || string.IsNullOrEmpty(this.pwd))
            {
                throw new Exception("连接失败!");
            }
            
            if (string.IsNullOrEmpty(this.dbName))
            {
                CONNSTR = con1.Format(new { server = this.server, uid = this.uid, pwd = this.pwd });
                
            }
            else
            {
                CONNSTR = con2.Format(new { server = this.server, uid = this.uid, pwd = this.pwd, database = this.dbName });
            }
            ConnectionString = con1.Format(new { server = this.server, uid = this.uid, pwd = this.pwd });
            SERVER = server;
            return CONNSTR;
        }

        public static string BuilderConnectionString(string selectdb)
        {
            return $"{ConnectionString};database={selectdb}";
        }

        public string GetDBName()
        {
            return server;
        }
    }
}
